package com.scalar.chiptrack.adaptor.ikanos.jsi;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.dao.InventoryLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Date;
import java.io.File;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 19 Sep, 2009
 * Time: 10:23:24 AM
 * To change this template use File | Settings | File Templates.
 */
public class JSITWDataParser extends JobHandler implements AdaptorConstants
{
    private HashMap<String, InventoryLot> m_fgDataMap = new HashMap<String, InventoryLot>();
    private HashMap<String, ShippedLot> m_fgShipDataMap = new HashMap<String,ShippedLot>();
    private static Logger m_parserLogger    = null;
    private String m_dataOutputDir          = null;

    public JSITWDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir( VENDOR_NAME_JSI_TW, LOCATION_TYPE_FINISHED_GOODS );
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_parserLogger = AdaptorUtils.getDataParserLogger( m_dataOutputDir,VENDOR_NAME_JSI_TW );
            InventoryLotDAO.setLogger( m_parserLogger );
            AdaptorUtils.setLogger( m_parserLogger );
            ShippedLotDAO.setLogger( m_parserLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading/creating JSI output directory from database, Exception: " + se);
            throw se;
        }
    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main( String args[] ) throws Exception
    {
        try
        {
            new JSITWDataParser().execute();
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    //Execute Method
   public void execute() throws Exception
   {
       AdaptorUtils.printHeader(VENDOR_NAME_JSI_TW, CONSTANT_PARSER );

       File doneDestDir = new File( m_dataOutputDir + "/done" );

       File wipDataoutDir = new File( m_dataOutputDir );

       File[] fileList = wipDataoutDir.listFiles();

       if ( ( fileList == null ) || ( fileList.length <= 3 ) )
       {
           log( "No file found in directory: " + wipDataoutDir );
           throw new ScalarException( "No file found in directory: " + wipDataoutDir + "----\n\n" );
       }

       ArrayList<File> successFileList   = new ArrayList<File>();
       boolean success             = false;

       try
       {
           for ( int i = 0; i < fileList.length; i++ )
           {
               if ( fileList[i].isDirectory() == true )
               {
                   continue;
               }

               if ( fileList[i].getName() != null && fileList[i].getName().trim().startsWith(JSITWPOP3Adaptor.JSI_TW_WIP_FILE ) )
               {
                    parseFGInventoryReport( fileList[i].getAbsolutePath() );

                   successFileList.add( fileList[i] );
               }

               if ( fileList[i].getName() != null && fileList[i].getName().trim().startsWith(JSITWPOP3Adaptor.JSI_TW_SHIP_FILE ) )
               {
                    parseShippingReport( fileList[i].getAbsolutePath() );

                   successFileList.add( fileList[i] );
               }
           }
       }
       catch ( Exception e )
       {
           success = false;
           log( "ERROR!! ERROR!! ERROR!! While parsing and storing File " + e );
           e.printStackTrace();
           throw e;
       }
       // to save the FG lot tables
       try
       {
           if ( m_fgDataMap.isEmpty() == false )
           {
               log(" Updating Finshed Goods Lot Information");
               InventoryLotDAO.saveInventoryLot(null, m_fgDataMap.values().iterator(), LOCATION_TYPE_FG, VENDOR_NAME_JSI_TW );
               success = true;
           }
           else
           {
               InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_FG, VENDOR_NAME_JSI_TW  );
           }
      }
      catch (ScalarException se)
      {
          success = false;
          se.printStackTrace();
          log("ERROR!! ERROR!! ERROR!! Could not update Finshed Goods Lot information into database: " + se);
          throw se;
      }
      try
        {
            // Save FG Ship Information
            if ( m_fgShipDataMap.isEmpty() == false )
            {
                log( " Updating FG Shiping Lot Information" );
                ShippedLotDAO.saveShippedLot( null, m_fgShipDataMap.values().iterator() );
            }
            success = true;
            m_fgShipDataMap.clear();
            m_fgShipDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update FG Shipping Lot information into database: " + se );
            throw se;
        } 
      // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
      AdaptorDAO.sendAllNotifications( VENDOR_NAME_JSI_TW, true, true, true );

      // To Close the Drop Out Lots
      AdaptorDAO.closeDropOutLots( VENDOR_NAME_JSI_TW );

      int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( JSITWPOP3Adaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);

      // Update Adaptor_Run_Info table
      try
      {
            if ( success == true )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, JSITWPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
      }
      catch ( ScalarException se )
      {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, JSITWPOP3Adaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
       }
        // Move the successful files to 'done' directory
       if ( success )
       {
           AdaptorUtils.moveFilesToDone( successFileList, doneDestDir );
       }
   }//end of execute method


    private void parseFGInventoryReport(  String filePath ) throws Exception
    {
        if ( filePath == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result     = null;
        String partNumber       = null;
        String lotNumber        = null;
        InventoryLot inventoryLot = null;

        try
        {
            File shipFile = new File( filePath );
            if ( shipFile.exists() == false )
            {
                throw new ScalarException( filePath + " doesnt exist" );
            }

            log( "\nFound " + filePath );
            log( "Parsing the file for FG Invnetory Report..." );
            System.out.println( "\nFound " + filePath );
            System.out.println( "Parsing the file for FG Inventory Report..." );

            Parser parser = ParserFactory.getXLSParser( shipFile );

            ArrayList sheetNamesList = ((XLSParserImpl)parser).getSheetNamesList();

            for(int i= 0; i< sheetNamesList.size(); i++ )
            {
                String sheetName = (String)sheetNamesList.get( i );
				//System.out.println("sheetName = " + sheetName);
                if ( sheetName != null && "FG".equalsIgnoreCase(sheetName.trim() ) ) /*sheetName.indexOf("Summary") == -1 && sheetName.indexOf("summary") == -1 && sheetName.indexOf("Sheet") == -1
                         && sheetName.indexOf("Non-Conformance") == -1 && sheetName.indexOf("Engineering") == -1 && sheetName.indexOf("PICKING") == -1*/
						 
                {
                    ((XLSParserImpl)parser).setHeaderRowIdx(2);
                    ((XLSParserImpl)parser).setDataStartRowIdx(3);

                    result = ((XLSParserImpl)parser).parse( sheetName );
                    
                    //System.out.println("result.getHeadings() = " + result.getHeadings());
                    
                     while ( result.next() )
                     {
                         partNumber = result.getString("Ikanos Mfg part no.");
                         lotNumber  = result.getString("Wafer Lot Number");
                         if ( partNumber != null && partNumber.trim().length() > 2 && lotNumber != null && lotNumber.trim().length() >0  )
                         {
                            log("In FG " + lotNumber );

                            inventoryLot = m_fgDataMap.get( partNumber + lotNumber );

                            if( inventoryLot == null )
                            {
                                inventoryLot = new InventoryLot( VENDOR_NAME_JSI_TW,  LOCATION_TYPE_FG);
                                m_fgDataMap.put( partNumber + lotNumber , inventoryLot );
                            }

                            int quantity = 0;
                            if (inventoryLot.getQtyIn() != null)
                            {
                                try
                                {
                                    quantity = Integer.parseInt(inventoryLot.getQtyIn());
                                }
                                catch (NumberFormatException ignore) {
                                }
                                quantity += result.getInt("Qty Available");

                            }
                            else
                            {
                                quantity = result.getInt("Qty Available");
                            }

                            if (quantity > 0 )
                            {
                                inventoryLot.setPartNumber( partNumber );
                                inventoryLot.setLotNumber( lotNumber );
                                inventoryLot.setQtyIn(quantity + "");
                                if ( result.getDate("Date of Receipt") != null )
                                {
                                    inventoryLot.setDateIn( StringUtils.formatDateToString(result.getDate("Date of Receipt")) );
                                }

                                inventoryLot.setFabLotNumber( lotNumber );
                                //inventoryLot.setStage(result.getString("Storage Location") );
                                inventoryLot.setDateCode( result.getString("Date Code"));
                                if ( sheetName.indexOf("Non-Conformance") != -1 )
                                {
                                    inventoryLot.setStatus( LOT_STATUS_HOLD );
                                }
                                else
                                {
                                    inventoryLot.setStatus( LOT_STATUS_RUNNING );
                                }
                                if ( sheetName.startsWith("Engineering") )
                                {
                                    inventoryLot.setLotCategory( LOT_CATEGORY_TYPE_ENGG );
                                }
                                else
                                {
                                    inventoryLot.setLotCategory( LOT_CATEGORY_TYPE_PROD );
                                }
                            }
                         }
                    }

                }
            }
        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
            throw ex;
        }
    } // end of prase parseReport method

    private void parseShippingReport(  String filePath ) throws Exception
    {
        if ( filePath == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result     = null;
        String partNumber       = null;
        String lotNumber        = null;
        ShippedLot shippedLot   = null;

        try
        {
            File shipFile = new File( filePath );
            if ( shipFile.exists() == false )
            {
                throw new ScalarException( filePath + " doesnt exist" );
            }

            log( "\nFound " + filePath );
            log( "Parsing the file for FG Shipment Report..." );
            System.out.println( "\nFound " + filePath );
            System.out.println( "Parsing the file for FG Shipment Report..." );

            Parser parser = ParserFactory.getXLSParser( shipFile );

            ArrayList sheetNamesList = ((XLSParserImpl)parser).getSheetNamesList();

            for(int i= 0; i< sheetNamesList.size(); i++ )
            {
                String sheetName = (String)sheetNamesList.get( i );

                if ( sheetName != null && sheetName.indexOf("Pending") == -1 )
                {
                    ((XLSParserImpl)parser).setHeaderRowIdx(4);
                    ((XLSParserImpl)parser).setDataStartRowIdx(5);

                    result = ((XLSParserImpl)parser).parse( sheetName );

                     while ( result.next() )
                     {
                         partNumber = result.getString("MANUFACTURING ITEM");
                         lotNumber  = result.getString("Lot No");
                         String shipDate = null;
                         String nextLocation = null;
                         String shipdocNo    = null;
                         String actualShipDate = null;
                         if (result.getDate("SHIP DATE") != null)
                         {
                             shipDate = StringUtils.formatDateToString(result.getDate("SHIP DATE"));
                         }
                         else
                         {
                             shipDate = StringUtils.formatDateToString( new Date());
                         }
                         if ("ON HOLD".equalsIgnoreCase(result.getString("Actual ship out Date"))  || "ADVANCED".equalsIgnoreCase(result.getString("Actual ship out Date"))
                                 || "CANCEL".equalsIgnoreCase(result.getString("Actual ship out Date")) )
                         {
                             actualShipDate = null;
                         }
                         else if (result.getDate("Actual ship out Date") != null )
                         {
                             actualShipDate = StringUtils.formatDateToString(result.getDate("Actual ship out Date"));
                         }
                         nextLocation = result.getString("SHIP TO");
                         shipdocNo = result.getString("SR NUMBER");

                         if ( partNumber != null && partNumber.trim().length() > 2 && lotNumber != null && lotNumber.trim().length() >0
                                 && actualShipDate != null && actualShipDate.trim().length() > 0 )
                         {
                                shippedLot = (ShippedLot) m_fgShipDataMap.get(partNumber + lotNumber + actualShipDate + nextLocation + shipdocNo);
                                if (shippedLot == null)
                                {
                                    shippedLot = new ShippedLot(VENDOR_NAME_JSI_TW, LOCATION_TYPE_FINISHED_GOODS );
                                    m_fgShipDataMap.put(partNumber + lotNumber + actualShipDate+ nextLocation + shipdocNo, shippedLot);
                                }

                                int quantity = 0;
                                if ( shippedLot.getShipQty() != null )
                                {
                                   try
                                   {
                                       quantity = Integer.parseInt( shippedLot.getShipQty() );
                                   }
                                   catch ( NumberFormatException ignore )
                                   {
                                       quantity = 0;
                                   }
                                   try
                                   {
                                       quantity += result.getInt("Qty");
                                   }
                                   catch ( NumberFormatException ignore )
                                   {
                                       quantity = 0;
                                   }
                                }
                                else
                                {
                                   try
                                   {
                                       quantity = result.getInt("Qty");
                                   }
                                   catch ( NumberFormatException ignore )
                                   {
                                       quantity = 0;
                                   }
                                }
                                if ( quantity > 0 )
                                {
                                    shippedLot.setLotNumber( lotNumber );
                                    shippedLot.setPartNumber( partNumber );
                                    shippedLot.setShipDate( actualShipDate );
                                    shippedLot.setShipQty( quantity + "");
                                    shippedLot.setShippingDoc( shipdocNo );
                                    shippedLot.setMawb( result.getString("MAWB NUMBER"));
                                    shippedLot.setHawb( result.getString("HAWB NUMBER") );
                                    shippedLot.setFlightNumber( result.getString("FLIGHT"));
                                    shippedLot.setNextLocation( nextLocation );
                                    shippedLot.setFabLotNumber( lotNumber );
                                    shippedLot.setProcessType( LOCATION_TYPE_FG );
                                }
                         }
                    }

                }
            }
        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
            throw ex;
        }
    } // end of prase parseReport method

   private static void log( String message )
    {

        if ( message == null ) return;

        if ( m_parserLogger != null )
        {
            synchronized ( m_parserLogger )
            {
                m_parserLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}

